<?php
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")."GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-type: application/json");

require_once 'dbCon.php';

//wurde ein item übermittelt
if (isset($_POST['data'])) {
    if ($item = json_decode(stripslashes($_POST['data']), true)) {
    	
    	$pref = $item['prefix'];
		
		//name der tabelle
		$table = '';
		switch ($pref) {
			case 'ctg':
				$table = '`ak_categories`';
				break;
			case 'prj':
				$table = '`ak_projects`';
				break;
			case 'btn':
				$table = '`ak_buttons`';
				break;
		}
		
		//Information über die Tabellenspalten
		$query = 'SHOW COLUMNS FROM '.$table;
		if($result = mysql_query($query)) {
			//Query erstellen
			$i = 0;
			$query = 'INSERT INTO `'.$db.'`.'.$table.' (';
			while ($row = mysql_fetch_assoc($result)) {
				$db_key = $row['Field'];
				$pos = strpos($db_key,'_')+1;
				$item_key = substr($row['Field'], $pos);
				if($i == 0) $query = $query.'`'.$db_key.'`';
				else $query = $query.', `'.$db_key.'`';
				$i++;
			}
			$query = $query.') VALUES ( ';
			//den data pointer auf den anfang der ergebnisse zurücksetzen
			mysql_data_seek($result, 0);
			$i = 0;
			while ($row = mysql_fetch_assoc($result)) {
				$db_key = $row['Field'];
				$pos = strpos($db_key,'_')+1;
				$item_key = substr($row['Field'], $pos);
				if($i == 0) $query = $query.
							'\''.mysql_real_escape_string($item[$item_key]).'\'';
				else $query = $query.
							', \''.mysql_real_escape_string($item[$item_key]).'\'';
				$i++;
			}
			$query = $query.')';
			$json['query'] = $query;
			
			//query ausführen
			if($result = mysql_query($query)) {
				$query = 'SELECT LAST_INSERT_ID() FROM '.$table;
				if ($result = mysql_query($query)) {
					$row = mysql_fetch_row($result);
					$json['id'] = $row[0];
					$json['result'] = 1;
				} else {
					$json['error'] = 'new ID query failed, '.$result;
					$json['result'] = 0;
				}
			} else {
				$json['error'] = 'save to database failed: '.mysql_error();
				$json['result'] = 0;
			}
		} else {
			$json['result'] = 0;
			$json['error'] = 'Get Column Info failed: '.mysql_error();
		}
	} else {
		$json = array('result' => 0, 'error' => 'decode json failed');
	}
} else {
	$json = array('result' => 0, 'error' => 'parameter missing: data = "'
											.$_POST['data'].'"');
}
// Datenbankverbindung schließen
mysql_close($conn);
$encoded = json_encode($json);
echo $encoded;
?>